﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using System.Data;
using System.Collections;
using System.IO;
using System.Text;

using Web.SystemConfig.ArchiveCode;
using ePlanet.ArchiveMange.Models;
using ePlanet.ArchiveMange.Services;
using DreamBuilder.Core.Container;
using Microsoft.Practices.Unity;
using ePlanet.ArchiveMange.Enum;
using CommonModule;
using ePlanet.SingleWell.Services;
using ePlanet.SingleWell.Models;

namespace Web.Views.ArchiveFlowView
{
    public partial class PrintJuanCatagoryView : PageBase
    {
        private const string _pageBreakHTML = @"<hr align='center' width='100%' size='1' noshade style='display:none;' />
    <div style='page-break-after:always;'></div>";

        private const string _rowItemFmt = @"<tr><td style='text-align:center;'>{0}</td><td style='text-align:center;'>{1}</td><td style='text-align:center;'>{2}</td><td class='cellPadding'>{3}</td><td style='text-align:center;'>{4}</td><td style='text-align:center;'>{5}</td><td style='text-align:center;'>{6}</td></tr>";

        private const int _pageCount = 15;

        [Dependency]
        public IArchiveMenuService ArchiveMenuService
        {
            get;
            set;
        }

        private int _baseArchiveTypeId;

        public int BaseArchiveTypeId
        {
            get
            {
                if (_baseArchiveTypeId == 0)
                {
                    _baseArchiveTypeId = ArchiveMenuService.GetArchiveBaseIDById(int.Parse(Request.QueryString["archiveType"]));
                }
                return _baseArchiveTypeId;
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            WriteUserLog(string.Format("用户{0}查看了{1}类型档案的企业目录", CurrentUser.Real_Name, BaseArchiveTypeId), OracleLogType.ArchiveManage);
            DataTable archiveTable = null;
            ArrayList idList = null;
            if (Request.QueryString["from"].Equals("dazl"))     //信息中心-E6
            {
                idList = Session["dazl_jnml_selectedkeys"] as ArrayList;
            }
            else if (Request.QueryString["from"].Equals("dasj")) //档案上交 基层-信息中心
            {
                idList = Session["dasj_jnml_selectedkeys"] as ArrayList;
            }
            else if (Request.QueryString["from"].Equals("dayj")) //档案移交 机关-信息中心
            {
                idList = Session["dayj_jnml_selectedkeys"] as ArrayList;
            }
            else if (Request.QueryString["from"].Equals("sjgl")) //数据管理
            {
                idList = Session["sjgl_jnml_selectedkeys"] as ArrayList;
            }

            string fmtHTML = File.ReadAllText(
                Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Views\ArchiveFlowView\PrintJuanCatagoryTemplate.htm"));

            if (string.IsNullOrEmpty(fmtHTML.Trim()))
            {
                Alert("缺少文件！无法打印！");
                return;
            }

            // 构造打印HTML
            StringBuilder sb = new StringBuilder();
            
            //页号
            int pageIndex = 1;

            for (int i = 0; i < idList.Count; i++ )
            {
                archiveTable = ArchiveBusiHelper.Instance.GetPageFileByDataId(
                    idList[i].ToString(), BaseArchiveTypeId);

                if (archiveTable == null 
                    || archiveTable.Rows.Count == 0) continue;
                DataView dv = archiveTable.AsDataView();
                dv.Sort = "ORDERNUM ASC";
                archiveTable = dv.ToTable();

                List<string> trTextList = new List<string>();
                int iCount = 0;

                int rowIndex = 0;
                foreach (DataRow row in archiveTable.Rows)
                {
                    iCount++;
                    rowIndex++;

                    trTextList.Add(string.Format(_rowItemFmt, rowIndex, row["DOCUMENTNUM"], row["PUBLISHER"],
                        row["title"], 
                        row["PUBLISHTIME"] == DBNull.Value ? string.Empty: Convert.ToDateTime(row["PUBLISHTIME"]).ToString("yyyy-MM-dd"), 
                        row["PAGENUM"], string.Empty));

                    if (iCount == _pageCount)
                    {
                        sb.Append(fmtHTML.Replace("{ITEMS}", string.Join(" ", trTextList.ToArray())));
                        trTextList.Clear();
                        sb.Append(_pageBreakHTML);
                        if (pageIndex > 1) sb.Append("<br />");
                        iCount = 0;
                        pageIndex++;
                    }
                }

                if (trTextList.Count() > 0)
                {
                    int trCount = trTextList.Count();
                    while (trCount < _pageCount)
                    {
                        trTextList.Add(string.Format(_rowItemFmt, string.Empty, string.Empty, string.Empty,
                            string.Empty, string.Empty, string.Empty, string.Empty));
                        trCount = trTextList.Count();
                    }
                    sb.Append("<br />");
                    sb.Append(fmtHTML.Replace("{ITEMS}", string.Join(" ", trTextList.ToArray())));
                    trTextList.Clear();
                    //sb.Append(_pageBreakHTML);
                }

                //sb.Append(_pageBreakHTML);
				
				// 若不是最后一卷，则添加换行符
				if(i + 1 < idList.Count)
				{
                    sb.Append(_pageBreakHTML);
					sb.Append("<br />");
				}
            }

            if (sb.ToString().Trim().Length == 0)
            {
                ClientScript.RegisterStartupScript(this.GetType(), "print",
                "<script type='text/javascript' > alert('没有卷内件，无法打印！'); </script>");
                return;
            }

            string printText = File.ReadAllText(Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory, @"Views\ArchiveFlowView\PrintJuanCatagoryTemplateFrame.htm"));

            Session["jnmlPrint"] = printText.Replace("{content}", sb.ToString());
            ClientScript.RegisterStartupScript(this.GetType(), "print",
                "<script type='text/javascript' > window.open('PageForPrint.aspx?from=jnml','newpage'); </script>");
        }

    }
}